package com.fiwizone.ultimateshoppinglist;

import java.util.Formatter;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class ItemList extends ListActivity {
	private static final int ACTIVITY_CREATE=0;
    private static final int ACTIVITY_EDIT=1;
    
	// Menu item ids
    public static final int MENU_ITEM_DELETE = Menu.FIRST;
    public static final int MENU_ITEM_INSERT = Menu.FIRST + 1;
    
	private ShoppingData mDbHelper;
	private TextView mRunningTotal;
	private Long mListId;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDbHelper = new ShoppingData(this);
        mDbHelper.open();
              
        setContentView(R.layout.item_list);
        
        mRunningTotal = ((TextView) findViewById(R.id.running_total));
        
        // Inform the list we provide context menus for items
        registerForContextMenu(getListView());
        
        mListId = savedInstanceState != null ? savedInstanceState.getLong(ShoppingData.KEY_LISTID) : null;
		if (mListId == null) {
			Bundle extras = getIntent().getExtras();            
			mListId = extras != null ? extras.getLong(ShoppingData.KEY_LISTID) : null;
		}
		
		fillData();
    }
    
    private void fillData() {
        // Get all of the rows from the database and create the item list
    	Cursor cursor = mDbHelper.fetchAllListItems(mListId);
        startManagingCursor(cursor);
        
        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{ShoppingData.KEY_TITLE, ShoppingData.KEY_COST};
        
        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{android.R.id.text1, R.id.cost};
        
        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter items = 
        	    new SimpleCursorAdapter(this, R.layout.item_list_item, cursor, from, to);
        setListAdapter(items);
        
        Cursor total = mDbHelper.fetchListTotal(mListId);
        startManagingCursor(total);
        Float totalCost = total.getFloat(total.getColumnIndexOrThrow(ShoppingData.KEY_COST));
        
        Formatter fmt = new Formatter();
        fmt.format("%.2f", totalCost);
        mRunningTotal.setText(fmt.toString());
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        // This is our one standard application action -- inserting a
        // new note into the list.
        menu.add(0, MENU_ITEM_INSERT, 0, R.string.menu_insert_item)
                .setIcon(android.R.drawable.ic_menu_add);

        return true;
    }
    
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
        case MENU_ITEM_INSERT:
        	createListItem();
            return true;
        }
       
        return super.onMenuItemSelected(featureId, item);
    }
    
    @Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, MENU_ITEM_DELETE, 0, R.string.menu_delete);
	}

    @Override
	public boolean onContextItemSelected(MenuItem item) {
		switch(item.getItemId()) {
    	case MENU_ITEM_DELETE:
    		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	        mDbHelper.deleteListItem(info.id);
	        fillData();
	        return true;
		}
		
		return super.onContextItemSelected(item);
	}
    
    private void createListItem() {
        Intent i = new Intent(this, ItemEdit.class);
        i.putExtra(ShoppingData.KEY_LISTID, mListId);
        startActivityForResult(i, ACTIVITY_CREATE);
    }
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Intent i = new Intent(this, ItemEdit.class);
        i.putExtra(ShoppingData.KEY_ROWID, id);
        startActivityForResult(i, ACTIVITY_EDIT);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        fillData();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong(ShoppingData.KEY_LISTID, mListId);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        fillData();
    }
}